/**
 * 防抖函数
 */
export function debounce<T extends (...args: any[]) => any>(
    func: T,
    wait: number
  ): (...args: Parameters<T>) => void {
    let timeout: number | null = null
    
    return function(this: any, ...args: Parameters<T>) {
      if (timeout) clearTimeout(timeout)
      
      timeout = setTimeout(() => {
        func.apply(this, args)
      }, wait)
    }
  }
  
  /**
   * 节流函数
   */
  export function throttle<T extends (...args: any[]) => any>(
    func: T,
    wait: number
  ): (...args: Parameters<T>) => void {
    let previous = 0
    
    return function(this: any, ...args: Parameters<T>) {
      const now = Date.now()
      if (now - previous > wait) {
        func.apply(this, args)
        previous = now
      }
    }
  }
  
  /**
   * 格式化时间
   */
  export function formatTime(date: Date | string | number, format = 'YYYY-MM-DD HH:mm:ss'): string {
    const d = new Date(date)
    const year = d.getFullYear()
    const month = String(d.getMonth() + 1).padStart(2, '0')
    const day = String(d.getDate()).padStart(2, '0')
    const hour = String(d.getHours()).padStart(2, '0')
    const minute = String(d.getMinutes()).padStart(2, '0')
    const second = String(d.getSeconds()).padStart(2, '0')
    
    return format
      .replace('YYYY', String(year))
      .replace('MM', month)
      .replace('DD', day)
      .replace('HH', hour)
      .replace('mm', minute)
      .replace('ss', second)
  }
  
  /**
   * 手机号脱敏
   */
  export function maskPhone(phone: string): string {
    if (!phone || phone.length !== 11) return phone
    return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
  }
  
  /**
   * 深拷贝（基于JSON，简单高效，但会忽略undefined、function等）
   */
  export function deepClone<T>(obj: T): T {
    // 简单的类型或空值，直接返回
    if (obj === null || typeof obj !== 'object') {
      return obj
    }
    try {
      return JSON.parse(JSON.stringify(obj))
    } catch (error) {
      console.error('深拷贝失败:', error)
      // 出现异常（如循环引用），可以根据场景返回原始对象或null/undefined
      return obj 
    }
  }
  
  /**
   * 生成唯一ID
   */
  export function generateId(): string {
    return Date.now().toString(36) + Math.random().toString(36).substr(2)
  }